﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsTest
{
    using AForge.Video.DirectShow;
    using AForge.Controls;
    using AForge.Video;
    using System.Threading;
    using System.Drawing.Imaging;
    //using AForge.Video.VFW;
    using VideoFootage;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //private AVIWriter writer;

        Accord.Video.FFMPEG.VideoFileWriter videoWriter;
        private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
        {

        }
        FilterInfoCollection videoDevices;//视频相关
        private List<VideoDeviceLst> deviceLsts;
        private void Form1_Load(object sender, EventArgs e)
        {
            //GraphicsPath gp = new GraphicsPath();
            //Rectangle rectg = new Rectangle( new Point( this.GbxVideo.Location.X, this.GbxVideo.Location.Y), new Size(GbxVideo.Width-50, GbxVideo.Height-50));
            //gp.AddEllipse(rectg);
            //GbxVideo.Region = new Region(gp);

            deviceLsts = new List<VideoDeviceLst>();
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count == 0) {
                MessageBox.Show("请连接视频!","提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (videoDevices.Count > 0) {

                for (int n = 0; n < videoDevices.Count; n++) {
                    VideoDeviceLst lst = new VideoDeviceLst()
                    {
                        MonString = videoDevices[n].MonikerString,
                        DeviceName = videoDevices[n].Name
                    };
                    deviceLsts.Add(lst);
                    ComboxVideo.Items.Add(videoDevices[n].Name);
                }
            }
            ComboxVideo.Text = videoDevices[0].Name;
            ComBoxframe.SelectedText = "20";
           
        }
        VideoCaptureDevice _videoCaptureDevice;
        public void StartCameras() {
            string monstr = deviceLsts.Where(x => x.DeviceName == ComboxVideo.Text).FirstOrDefault().MonString;
            _videoCaptureDevice = new VideoCaptureDevice(monstr)
            {
                DesiredFrameSize = new Size(1280, 720),//可做页面设置
                DesiredFrameRate = 35


            };
            videoSourcePlayer1.VideoSource = _videoCaptureDevice;
            videoSourcePlayer1.Start();
          
           // timervideo.Enabled = true;
        }
        Thread _mythread;
        private void btnstartCameras_Click(object sender, EventArgs e)
        {
            try
            {
                btnstartCameras.Enabled = false;
                btnstopCameras.Enabled = true;
                StartCameras();
                LogHelper.WriteLog(typeof(Form1), "开始录制视频");
                string path = Application.StartupPath + "\\Video";
                if (!File.Exists(path))
                {

                    Directory.CreateDirectory(path);
                }
                string VideoPath = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + "_sp_.avi";
                //writer = new AVIWriter();
                videoWriter = new Accord.Video.FFMPEG.VideoFileWriter();
                videoWriter.Open(VideoPath, 1280, 720, 30,Accord.Video.FFMPEG.VideoCodec.WMV2); //可设置
                _mythread = new Thread(new ThreadStart(TestStart1));
                _mythread.Start();
            }
            catch (Exception ex) {
                //LogHelper.WriteLogError(typeof(Form1), ex);
            }
        }
        //public void TestStart() {

        //    MicroTimer _microTimer = new MicroTimer();
        //    _microTimer.MicroTimerElapsed += new MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent1);
        //    _microTimer.Interval = 49000;
        //    _microTimer.Enabled = true;
        //   // Thread.Sleep(15000); //录制时间为15秒
        //    _microTimer.Enabled = false;
        //}
        MicroTimer _microTimer = new MicroTimer();
        public void TestStart1()
        {
           
          //  MicroTimer _microTimer = new MicroTimer();
            //_microTimer.MicroTimerElapsed += new MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent1);
            //_microTimer.Interval = 49000;
            //_microTimer.Enabled = true;
         
        }
        Bitmap bmp1 = null;
  
        //private void OnTimedEvent1(object sender, MicroTimerEventArgs timerEventArgs)
        //{
        //    try
        //    {
        //        videoWriter.WriteVideoFrame(bmp1);
        //    }
        //    catch (Exception ex)
        //    {

        //        LogHelper.WriteLogError(typeof(Form1), ex);
        //    }
        //}

        private void btnstopCameras_Click(object sender, EventArgs e)
        {
            if (videoSourcePlayer1.IsRunning) {
                if (_mythread.IsAlive) _mythread.Abort();
              
                timervideo.Enabled = false;
                _microTimer.Enabled = false;
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.WaitForStop();
                videoWriter.Close();
                videoWriter.Dispose();

                btnstartCameras.Enabled= true;
                btnstopCameras.Enabled = false;
            }

        }

        private void btnexit_Click(object sender, EventArgs e)
        {
            if (videoSourcePlayer1.IsRunning)
            {
                MessageBox.Show("请先停止录制视频","提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            this.Dispose();
            this.Close();
        }
        private const int statLength = 15;
        private int[] statCount1 = new int[statLength];
        private int statIndex = 0;
        private int statReady = 0;
        /// <summary>
        /// 可删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timervideo_Tick(object sender, EventArgs e)
        {
            IVideoSource videoSource1 = videoSourcePlayer1.VideoSource;

            if (videoSource1 != null)
            {
                statCount1[statIndex] = videoSource1.FramesReceived;
            }

            if (++statIndex >= statLength)
                statIndex = 0;
            if (statReady < statLength)
                statReady++;

            float fps1 = 0;

            for (int i = 0; i < statReady; i++)
            {
                fps1 += statCount1[i];

            }
            fps1 /= statReady;

            statCount1[statIndex] = 0;
        }

        private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            try
            {
                bmp1 = (Bitmap)image.Clone();
            }
            catch (Exception ex)
            {

                //LogHelper.WriteLogError(typeof(Form1), ex);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (videoSourcePlayer1.IsRunning)
            {
                if (_mythread.IsAlive) _mythread.Abort();

                timervideo.Enabled = false;
                _microTimer.Enabled = false;
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.WaitForStop();
                videoWriter.Close();
                videoWriter.Dispose();
            }

            this.Dispose();
        }
        void Map() {

            //Rectangle rectangle=new Rectangle()
        }
        private void videoSourcePlayer1_NewFrame_1(object sender, ref Bitmap image)
        {
            try
            {
              //  bmp1 = (Bitmap)image.Clone();

                videoWriter.WriteVideoFrame(image);
            }
            catch (Exception ex )
            {

                LogHelper.WriteLogError(typeof(Form1), ex);
            }
        }

        private void btnphotograph_Click(object sender, EventArgs e)
        {

            try
            {
                if (_videoCaptureDevice == null)
                    return;
                Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();
                string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".jpg";//DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".jpg";  
                if (!File.Exists(Application.StartupPath + "\\CamersImage")) { Directory.CreateDirectory(Application.StartupPath + "\\CamersImage"); }
                bitmap.Save(Application.StartupPath + "\\" + fileName, ImageFormat.Jpeg);
                bitmap.Dispose();
                pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\" + fileName);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError(typeof(Form1), ex);
             
            }
        }
    }

    public class VideoDeviceLst
    {
        public string MonString { get; set; }

        public string DeviceName { get; set; }
    }
} 
